package com.haixiaoke.smartLock.haixiaoke;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.haixiaoke.common.core.redis.RedisCache;
import com.haixiaoke.common.core.text.Convert;
import com.haixiaoke.common.exception.ServiceException;
import com.haixiaoke.common.utils.RequestAesUtils;
import com.haixiaoke.domain.*;
import com.haixiaoke.service.*;
import com.haixiaoke.smartLock.base.SmartLockBasicsService;
import com.haixiaoke.vo.YltAuthVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static cn.hutool.crypto.SecureUtil.sha1;

/**
 * 嗨小克智能锁接口
 * xiaolong
 * 2023-06-06
 */
@Slf4j
@Service
public class SmartLockHXKService implements SmartLockBasicsService {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private OSSClient ossClient;
    @Value("${haiXiaoKe.url}")
    private String haiXiaoKeUrl;
    @Value(("${haiXiaoKe.appid}"))
    private String haiXiaoKeAppid;
    @Value("${haiXiaoKe.appSecret}")
    private String haiXiaoKeAppSecret;


    @Autowired
    private ISmartLockCardService iSmartLockCardService;
    @Autowired
    private ISmartLockPwdService iSmartLockPwdService;
    @Autowired
    private ISmartLockFaceService iSmartLockFaceService;
    @Autowired
    private ILockYltAccreditService iLockYltAccreditService;
    @Autowired
    private ISmartLockService iSmartLockService;

    /**
     * 获取嗨小克平台token
     *
     * @return token
     */
    public String getToken() {
        String token = redisCache.getCacheObject("sys_haiXiaoKeToken");
        if (StringUtils.isEmpty(token)) {
            try {
                Map<String, Object> paramsMap = new HashMap<>(4);
                String nowTime = this.haiXiaoKeParseDate(null);
                paramsMap.put("appId", haiXiaoKeAppid);
                paramsMap.put("appSecret", haiXiaoKeAppSecret);
                paramsMap.put("sendTime", nowTime);
                paramsMap.put("randNonce", "123456");
                log.info("嗨小克--鉴权请求参数：{}", paramsMap);
                HttpResponse response = HttpRequest.post(haiXiaoKeUrl + "/login").body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
                log.info("嗨小克--鉴权响应参数：{}", response.body());
                if (HttpStatus.HTTP_OK == response.getStatus()) {
                    JSONObject jsonObject = JSONObject.parseObject(response.body());
                    Integer code = jsonObject.getInteger("code");
                    if (code == 0) {
                        JSONObject result = jsonObject.getJSONObject("result");
                        token = "Bearer " +result.getString("accessToken");
                        Integer expiresIn = result.getInteger("expiresIn");
                        redisCache.setCacheObject("sys_haiXiaoKeToken", token, expiresIn - 60, TimeUnit.MILLISECONDS);
                    } else {
                        log.error("嗨小克--鉴权请求响应数据异常：{}", jsonObject);
                    }
                } else {
                    log.error("嗨小克--鉴权请求失败，code：{}；body:{}", response.getStatus(), response.body());
                }
            } catch (Exception e) {
                log.error("嗨小克--鉴权请求异常：{}", e.getMessage(), e);
            }
        }
        return token;
    }

    @Override
    public String getSmartLock(SmartLock smartLock) {
        /*if (StrUtil.isEmpty(smartLock.getSn())) {
            log.error("智能锁的sn信息为空");
            return null;
        }*/
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("嗨小克--获取智能锁信息接口--token为空");
            return null;
        }
        try {
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("page", smartLock.getPageNum());
            paramsMap.put("pageSize", smartLock.getPageSize());
            if (StrUtil.isNotEmpty(smartLock.getSn())) {
                paramsMap.put("deviceMac", smartLock.getSn());
            }
            /*if (StrUtil.isNotEmpty(smartLock.getLockName())) {
                paramsMap.put("deviceName", smartLock.getLockName());
            }*/
            paramsMap.put("randNonce", "123456");
            /*String nowTime = this.haiXiaoKeParseDate();
            paramsMap.put("sendTime", nowTime);
            //表示获取最后更新时间后状态有新变化设备，用于减少每次同步的数量
            paramsMap.put("lastSyncTime", nowTime);*/
            log.info("嗨小克--获取智能锁信息请求参数：{}", paramsMap);
            HttpResponse response = HttpRequest.post(haiXiaoKeUrl + "/getDeviceList").header("Authorization", token).body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            log.info("嗨小克--获取智能锁信息响应参数：{}", response.body());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                Integer code = jsonObject.getInteger("code");
                if (code == 0) {
                    return response.body();
                } else {
                    log.error("嗨小克--查询门锁列表请求响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("嗨小克--查询门锁列表请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("嗨小克--查询门锁列表请求异常：{}", e.getMessage(), e);
        }
        return null;
    }

    public String getSmartLockByLockName(SmartLock smartLock) {
        /*if (StrUtil.isEmpty(smartLock.getSn())) {
            log.error("智能锁的sn信息为空");
            return null;
        }*/
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("嗨小克--获取智能锁信息接口--token为空");
            return null;
        }
        try {
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("page", smartLock.getPageNum());
            paramsMap.put("pageSize", smartLock.getPageSize());
            if (StrUtil.isNotEmpty(smartLock.getSn())) {
                paramsMap.put("deviceMac", smartLock.getSn());
            }
            if (StrUtil.isNotEmpty(smartLock.getLockName())) {
                paramsMap.put("deviceName", smartLock.getLockName());
            }
            paramsMap.put("randNonce", "123456");
            /*String nowTime = this.haiXiaoKeParseDate();
            paramsMap.put("sendTime", nowTime);
            //表示获取最后更新时间后状态有新变化设备，用于减少每次同步的数量
            paramsMap.put("lastSyncTime", nowTime);*/
            log.info("嗨小克--获取智能锁信息请求参数：{}", paramsMap);
            HttpResponse response = HttpRequest.post(haiXiaoKeUrl + "/getDeviceList").header("Authorization", token).body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            log.info("嗨小克--获取智能锁信息响应参数：{}", response.body());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                Integer code = jsonObject.getInteger("code");
                if (code == 0) {
                    return response.body();
                } else {
                    log.error("嗨小克--查询门锁列表请求响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("嗨小克--查询门锁列表请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("嗨小克--查询门锁列表请求异常：{}", e.getMessage(), e);
        }
        return null;
    }

    @Override
    public String getSmartLockDetails(SmartLock smartLock) {
        return null;
    }

    @Override
    public String getLockPassword(SmartLock smartLock) {
        return null;
    }

    @Override
    public String getBluetooth(SmartLock smartLock) {
        return null;
    }

    @Override
    public String deleteBle(SmartLock smartLock) {
        return null;
    }

    @Override
    public String addBluetooth(SmartLock smartLock) {
        return null;
    }

    @Override
    public String addFingerprint(SmartLock smartLock) {
        return null;
    }

    @Override
    public String sendFingerprint(SmartLock smartLock) {
        return null;
    }

    @Override
    public String deleteFingerprint(SmartLock smartLock) {
        return null;
    }

    @Override
    public String offlinePassword(SmartLock smartLock) {
        return null;
    }

    @Override
    public String remoteUnlock(SmartLock smartLock) {
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("嗨小克--授权智能锁用户密码接口--token为空");
            return "0";
        }

        try {
            Map<String, Object> paramsMap = new HashMap<>(4);
            String notTime = this.haiXiaoKeParseDate(null);
            paramsMap.put("sendTime", notTime);
            paramsMap.put("randNonce", "123456");
            paramsMap.put("deviceMac", smartLock.getSn());
            log.info("嗨小克--远程开门请求参数：{}", paramsMap);
            HttpResponse response = HttpRequest.post(haiXiaoKeUrl + "/lock/remoteOpenLock").header("Authorization", token).body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            log.info("嗨小克--远程开门响应参数：{}", response.body());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String code = jsonObject.getString("code");
                if ("0".equals(code)) {
                    return "1";
                } else {
                    log.error("嗨小克--远程开门请求响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("嗨小克--远程开门请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("嗨小克--远程开门请求异常：{}", e.getMessage(), e);
        }
        return "0";
    }

    @Override
    @Transactional
    public String addPassword(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();
        yltAuthVo.setFOpenByPassword(LockYltAccredit.AUTH_STATE_TRUE);
        yltAuthVo.setFOpenPassword(smartLock.getPassword());
        smartLock.setYltAuthVo(yltAuthVo);
        return addAuth(smartLock);

    }

    @Override
    public String deletePwd(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();

        if (LockYltAccredit.AUTH_STATE_FALSE.equals(yltAuthVo.getFOpenByIDCard()) &&
                LockYltAccredit.AUTH_STATE_FALSE.equals(yltAuthVo.getFOpenByICCard()) &&
                LockYltAccredit.AUTH_STATE_FALSE.equals(yltAuthVo.getFOpenByFace())) {
            return deleteAuth(smartLock);
        }

        yltAuthVo.setFOpenByPassword(LockYltAccredit.AUTH_STATE_FALSE);
        smartLock.setYltAuthVo(yltAuthVo);
        return addAuth(smartLock);
    }

    @Override
    public String addCard(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();
        if (SmartLock.CPU_CARD_TYPE.equals(smartLock.getCardType())) {
            yltAuthVo.setFOpenByICCard(LockYltAccredit.AUTH_STATE_TRUE);
            yltAuthVo.setFICCardNumber(smartLock.getCardNumber());
        } else if (SmartLock.IDENTITY_CARD_TYPE.equals(smartLock.getCardType())) {
            yltAuthVo.setFOpenByIDCard(LockYltAccredit.AUTH_STATE_TRUE);
            yltAuthVo.setFIDCardID(smartLock.getCardNumber());
        } else {
            log.error("五代锁--授权门卡数据异常：cardType：{}", smartLock.getCardType());
            throw new ServiceException("五代锁--授权门卡数据异常");
        }
        smartLock.setYltAuthVo(yltAuthVo);
        return addAuth(smartLock);
    }

    @Override
    public String deleteCard(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();
        if (SmartLock.CPU_CARD_TYPE.equals(smartLock.getCardType())) {
            if (LockYltAccredit.AUTH_STATE_FALSE.equals(yltAuthVo.getFOpenByPassword()) &&
                    LockYltAccredit.AUTH_STATE_FALSE.equals(yltAuthVo.getFOpenByIDCard()) &&
                    LockYltAccredit.AUTH_STATE_FALSE.equals(yltAuthVo.getFOpenByFace())) {
                return deleteAuth(smartLock);
            }
            yltAuthVo.setFOpenByICCard(LockYltAccredit.AUTH_STATE_FALSE);
        } else if (SmartLock.IDENTITY_CARD_TYPE.equals(smartLock.getCardType())) {
            if (LockYltAccredit.AUTH_STATE_FALSE.equals(yltAuthVo.getFOpenByPassword()) &&
                    LockYltAccredit.AUTH_STATE_FALSE.equals(yltAuthVo.getFOpenByICCard()) &&
                    LockYltAccredit.AUTH_STATE_FALSE.equals(yltAuthVo.getFOpenByFace())) {
                return deleteAuth(smartLock);
            }
            yltAuthVo.setFOpenByIDCard(LockYltAccredit.AUTH_STATE_FALSE);
        } else {
            log.error("五代锁--删除门卡数据异常：cardType：{}", smartLock.getCardType());
            throw new ServiceException("五代锁--删除门卡数据异常");
        }
        smartLock.setYltAuthVo(yltAuthVo);
        return addAuth(smartLock);
    }

    @Override
    public String getUnlockKey(SmartLock smartLock) {
        return null;
    }

    @Override
    public String addFaceImage(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();
        yltAuthVo.setFOpenByFace(LockYltAccredit.AUTH_STATE_TRUE);
        yltAuthVo.setFaceImage(smartLock.getFaceImage());
        smartLock.setYltAuthVo(yltAuthVo);
        return addAuth(smartLock);
    }

    @Override
    public String deleteFace(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();

        if (LockYltAccredit.AUTH_STATE_FALSE.equals(yltAuthVo.getFOpenByIDCard()) &&
                LockYltAccredit.AUTH_STATE_FALSE.equals(yltAuthVo.getFOpenByICCard()) &&
                LockYltAccredit.AUTH_STATE_FALSE.equals(yltAuthVo.getFOpenByPassword())) {
            return deleteAuth(smartLock);
        }

        yltAuthVo.setFOpenByFace(LockYltAccredit.AUTH_STATE_FALSE);
        smartLock.setYltAuthVo(yltAuthVo);
        return addAuth(smartLock);
    }

    @Override
    public String getTaskList(SmartLock smartLock) {
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("嗨小克--获取智能锁信息接口--token为空");
            return null;
        }
        try {
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("page", smartLock.getPageNum());
            paramsMap.put("pageSize", smartLock.getPageSize());
            if (StrUtil.isNotEmpty(smartLock.getSn())) {
                paramsMap.put("deviceMac", smartLock.getSn());
            }
            SimpleDateFormat fo = new SimpleDateFormat("yyyy-MM-dd");
            paramsMap.put("startTime",fo.format(smartLock.getStartTime()));
            paramsMap.put("endTime",fo.format(smartLock.getEndTime()));
            paramsMap.put("randNonce", "123456");
            String nowTime = this.haiXiaoKeParseDate(null);
            paramsMap.put("sendTime", nowTime);
            log.info("嗨小克--获取智能锁授权指令信息请求参数：{}", paramsMap);
            HttpResponse response = HttpRequest.post(haiXiaoKeUrl + "/lock/getTaskList").header("Authorization", token).body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            log.info("嗨小克--获取智能锁授权指令信息响应参数：{}", response.body());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                Integer code = jsonObject.getInteger("code");
                if (code == 0) {
                    return response.body();
                } else {
                    log.error("嗨小克--查询门锁列表请求响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("嗨小克--查询门锁列表请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("嗨小克--查询门锁列表请求异常：{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 添加智能锁用户授权
     *
     * @param smartLock
     * @return
     */
    public String addAuth(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("嗨小克--授权智能锁用户密码接口--token为空");
            return "0";
        }
        try {
            Map<String, Object> paramsMap = new HashMap<>(4);
            String notTime = this.haiXiaoKeParseDate(null);
            paramsMap.put("sendTime", notTime);
            paramsMap.put("randNonce", "123456");
            paramsMap.put("deviceMac", smartLock.getSn());
            //用户id
//            paramsMap.put("userIndex", smartLock.getIdentification());
            if (StrUtil.isNotEmpty(smartLock.getUserRole())) {
                paramsMap.put("userRole", smartLock.getUserRole());
            }
            if (StrUtil.isNotEmpty(smartLock.getMobile())) {
                paramsMap.put("mobile", smartLock.getMobile());
            }
            if (StrUtil.isNotEmpty(smartLock.getUserName())) {
                paramsMap.put("userName", smartLock.getUserName());
            }
            paramsMap.put("idNumber", smartLock.getIdentification());
            //身份证授权

            if (LockYltAccredit.AUTH_STATE_TRUE.equals(yltAuthVo.getFOpenByIDCard())) {
                // TODO: 2023/9/13 身份卡号 yltAuthVo.getFIDCardNumber()
                paramsMap.put("cardNo", yltAuthVo.getFICCardNumber());
            }
            //门卡授权
            if (LockYltAccredit.AUTH_STATE_TRUE.equals(yltAuthVo.getFOpenByICCard())) {
                paramsMap.put("cardNo", yltAuthVo.getFICCardNumber());
            }
            //密码授权
            if (LockYltAccredit.AUTH_STATE_TRUE.equals(yltAuthVo.getFOpenByPassword())) {
                paramsMap.put("password", yltAuthVo.getFOpenPassword());
            }
            String startTime = this.haiXiaoKeParseDate(yltAuthVo.getFBeginDate());
            String endTime = this.haiXiaoKeParseDate(yltAuthVo.getFEndDate() == null ? this.addTime(new Date()) : yltAuthVo.getFEndDate());
            smartLock.setStartTime(simpleDateFormat.parse(startTime));
            smartLock.setEndTime(simpleDateFormat.parse(endTime));
            paramsMap.put("startTime", startTime);
            paramsMap.put("endTime", endTime);
            HttpRequest authorization = HttpRequest.post(haiXiaoKeUrl + "/lock/addUser")
                    .header("Authorization", token).form(paramsMap);

            HttpResponse response;
            //人脸授权
            if (LockYltAccredit.AUTH_STATE_TRUE.equals(yltAuthVo.getFOpenByFace())) {
                // String faceImage = yltAuthVo.getFaceImage().split("https://xj-saas-images.oss-cn-qingdao.aliyuncs.com/")[1];
                // OSSObject object = ossClient.getObject("xj-saas-images", faceImage);
                File file = File.createTempFile("stream2file", ".jpg");

                byte[] imageData = HttpUtil.downloadBytes(yltAuthVo.getFaceImage());
                if (ObjectUtil.isEmpty(imageData)){
                    log.error("五代锁--人脸图片下载失败：{}", yltAuthVo.getFaceImage());
                }
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageData);

                try (FileOutputStream out = new FileOutputStream(file)) {
                    IOUtils.copy(byteArrayInputStream, out);
                }

                response = authorization.form("file", file).timeout(20000).execute();
                log.info("嗨小克--五代锁授权信息请求：{}，人脸：{}", paramsMap,yltAuthVo.getFaceImage());
                byteArrayInputStream.close();
            } else {
                log.info("嗨小克--五代锁授权信息请求：{}", paramsMap);
                response = authorization.timeout(20000).execute();
            }
            log.info("嗨小克--五代锁授权信息响应：{}", response.body());

            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String code = jsonObject.getString("code");
                if ("0".equals(code)) {
                    //维护数据库数据
                    this.addAuthInfo(smartLock);
                    return "1";
                } else {
                    log.error("嗨小克--五代锁授权信息请求响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("嗨小克--五代锁授权信息请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("嗨小克--五代锁授权信息请求异常：{}", e.getMessage(), e);
        }
        return "0";
    }

    public void addAuthInfo(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();

        // 亚略特用户授权信息
        LockYltAccredit yltAccredit = new LockYltAccredit();

        yltAccredit.setPwdUnlockState(yltAuthVo.getFOpenByPassword().longValue());
        yltAccredit.setIcCardUnlockState(yltAuthVo.getFOpenByICCard().longValue());
        yltAccredit.setFingerUnlockState(yltAuthVo.getFOpenByFinger().longValue());
        yltAccredit.setCardUnlockState(yltAuthVo.getFOpenByIDCard().longValue());
        yltAccredit.setBluetoothUnlockState(yltAuthVo.getFOpenByBLE().longValue());
        yltAccredit.setFaceUnlockState(yltAuthVo.getFOpenByFace().longValue());
        yltAccredit.setAuthStartTime(yltAuthVo.getFBeginDate());
        yltAccredit.setAuthEndTime(yltAuthVo.getFEndDate());
        yltAccredit.setIdentification(smartLock.getIdentification());

        // sn
        yltAccredit.setLockSn(smartLock.getSn());

        // 身份证号
        if (LockYltAccredit.AUTH_STATE_TRUE.equals(yltAuthVo.getFOpenByIDCard()) && StrUtil.isNotEmpty(yltAuthVo.getFIDCardID())) {
            SmartLockCard idCard = new SmartLockCard();
            idCard.setSn(smartLock.getSn());
            idCard.setIdentification(smartLock.getIdentification());
            idCard.setCardType(SmartLockCard.IDENTITY_CARD_TYPE);
            idCard.setCardNumber(yltAuthVo.getFIDCardID());
            idCard.setStartTime(yltAuthVo.getFBeginDate());
            idCard.setEndTime(yltAuthVo.getFEndDate());
            iSmartLockCardService.insertSmartLockCard(idCard);
        }

        // ic卡
        if (LockYltAccredit.AUTH_STATE_TRUE.equals(yltAuthVo.getFOpenByICCard()) && StrUtil.isNotEmpty(yltAuthVo.getFICCardNumber())) {
            SmartLockCard idCard = new SmartLockCard();
            idCard.setSn(smartLock.getSn());
            idCard.setIdentification(smartLock.getIdentification());
            idCard.setCardType(SmartLockCard.CPU_CARD_TYPE);
            idCard.setCardNumber(yltAuthVo.getFICCardNumber());
            idCard.setStartTime(yltAuthVo.getFBeginDate());
            idCard.setEndTime(yltAuthVo.getFEndDate());
            iSmartLockCardService.insertSmartLockCard(idCard);
        }

        // 密码
        if (LockYltAccredit.AUTH_STATE_TRUE.equals(yltAuthVo.getFOpenByPassword()) && StrUtil.isNotEmpty(yltAuthVo.getFOpenPassword())) {
            SmartLockPwd pwd = new SmartLockPwd();
            pwd.setSn(smartLock.getSn());
            pwd.setIdentification(smartLock.getIdentification());
            pwd.setGenerateType(SmartLockPwd.PASSWORD_GENERATE_TYPE_CUSTOM);
            pwd.setPassword(yltAuthVo.getFOpenPassword());
            pwd.setStartTime(yltAuthVo.getFBeginDate());
            pwd.setEndTime(yltAuthVo.getFEndDate());
            iSmartLockPwdService.insertSmartLockPwd(pwd);
        }

        //人脸
        if (LockYltAccredit.AUTH_STATE_TRUE.equals(yltAuthVo.getFOpenByFace()) && StrUtil.isNotEmpty(yltAuthVo.getFaceImage())) {
            SmartLockFace face = new SmartLockFace();
            face.setSn(smartLock.getSn());
            face.setIdentification(smartLock.getIdentification());
            face.setFaceImage(yltAuthVo.getFaceImage());
            face.setStartTime(yltAuthVo.getFBeginDate());
            face.setEndTime(yltAuthVo.getFEndDate());
            iSmartLockFaceService.insertSmartLockFace(face);
        }

        iLockYltAccreditService.insertLockYltAccredit(yltAccredit);
    }

    /**
     * 删除智能锁指定用户
     *
     * @param smartLock
     * @return
     */
    public String deleteAuth(SmartLock smartLock) {
        YltAuthVo yltAuthVo = smartLock.getYltAuthVo();
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("嗨小克--删除智能锁用户密码接口--token为空");
            return "0";
        }
        try {
            Map<String, Object> paramsMap = new HashMap<>(4);
            String notTime = this.haiXiaoKeParseDate(null);
            paramsMap.put("sendTime", notTime);
            paramsMap.put("randNonce", "123456");
            paramsMap.put("deviceMac", smartLock.getSn());
            paramsMap.put("idNumber", smartLock.getIdentification());
            log.info("嗨小克--删除智能锁用户密码请求参数：{}", paramsMap);
            HttpResponse response = HttpRequest.post(haiXiaoKeUrl + "/lock/removeUser").header("Authorization", token).body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            log.info("嗨小克--删除智能锁用户密码响应参数：{}", response.body());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String code = jsonObject.getString("code");
                if ("0".equals(code)) {
                    LockYltAccredit accredit = iLockYltAccreditService.selectLockYltAccreditByLockSNAndIdentification(smartLock.getSn(), yltAuthVo.getFAppUserID());
                    // 身份证授权
                    if (LockYltAccredit.AUTH_STATE_TRUE.longValue() == accredit.getCardUnlockState()) {
                        iSmartLockCardService.deleteSmartLockCardBySnAndIdentificationAndCardType(smartLock.getSn(), yltAuthVo.getFAppUserID(), SmartLockCard.IDENTITY_CARD_TYPE);
                    }

                    // ic卡授权
                    if (LockYltAccredit.AUTH_STATE_TRUE.longValue() == accredit.getIcCardUnlockState()) {
                        iSmartLockCardService.deleteSmartLockCardBySnAndIdentificationAndCardType(smartLock.getSn(), yltAuthVo.getFAppUserID(), SmartLockCard.CPU_CARD_TYPE);
                    }

                    // 密码授权
                    if (LockYltAccredit.AUTH_STATE_TRUE.longValue() == accredit.getPwdUnlockState()) {
                        iSmartLockPwdService.deleteSmartLockPwdBySnAndIdentification(smartLock.getSn(), yltAuthVo.getFAppUserID());
                    }

                    // 人脸授权
                    if (LockYltAccredit.AUTH_STATE_TRUE.longValue() == accredit.getFaceUnlockState()) {
                        iSmartLockFaceService.deleteSmartLockFaceBySnAndIdentification(smartLock.getSn(), yltAuthVo.getFAppUserID());
                    }
                    // ylt授权信息
                    iLockYltAccreditService.deleteLockYltAccreditById(accredit.getId());
                    return "1";
                } else {
                    log.error("嗨小克--删除门锁用户密码请求响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("嗨小克--删除门锁用户密码请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("嗨小克--删除门锁用户密码请求异常：{}", e.getMessage(), e);
        }
        return "0";
    }

    /**
     * 删除智能锁全部用户
     *
     * @param smartLock
     * @return
     */
    public String deleteAuthAll(SmartLock smartLock) {
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("嗨小克--删除智能锁全部用户密码接口--token为空");
            return "0";
        }
        try {
            Map<String, Object> paramsMap = new HashMap<>(4);
            String notTime = this.haiXiaoKeParseDate(null);
            paramsMap.put("sendTime", notTime);
            paramsMap.put("randNonce", "123456");
            paramsMap.put("deviceMac", smartLock.getSn());
            paramsMap.put("removeAllUser", smartLock.getDeleteUserFlag());
            log.info("嗨小克--删除智能锁全部用户密码请求参数：{}", paramsMap);
            HttpResponse response = HttpRequest.post(haiXiaoKeUrl + "/lock/removeAllUser").header("Authorization", token).body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            log.info("嗨小克--删除智能锁全部用户密码响应参数：{}", response.body());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String code = jsonObject.getString("code");
                if ("0".equals(code)) {
                    // 身份证授权
                    iSmartLockCardService.deleteSmartLockCardBySnAndIdentificationAndCardType(smartLock.getSn(), null, SmartLockCard.IDENTITY_CARD_TYPE);

                    // ic卡授权
                    iSmartLockCardService.deleteSmartLockCardBySnAndIdentificationAndCardType(smartLock.getSn(), null, SmartLockCard.CPU_CARD_TYPE);

                    // 密码授权
                    iSmartLockPwdService.deleteSmartLockPwdBySnAndIdentification(smartLock.getSn(), null);

                    //身份证授权
                    iSmartLockFaceService.deleteSmartLockFaceBySnAndIdentification(smartLock.getSn(), null);

                    //人脸授权
                    iSmartLockFaceService.deleteSmartLockFaceBySnAndIdentification(smartLock.getSn(), null);

                    // ylt授权信息
                    iLockYltAccreditService.deleteLockYltAccreditByLockSN(smartLock.getSn());

                    if (smartLock.getLockId() != null) {
                        iSmartLockService.deleteSmartLockByLockId(smartLock.getLockId());
                    }

                    return "1";
                } else {
                    log.error("嗨小克--删除门锁全部用户密码请求响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("嗨小克--删除门锁全部用户密码请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("嗨小克--删除门锁全部用户密码请求异常：{}", e.getMessage(), e);
        }
        return "0";
    }

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    public String haiXiaoKeParseDate(Date date) {
        if (date == null) {
            date = new Date();
        }
        return simpleDateFormat.format(date);
    }

    public Date addTime(Date nowTime) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(nowTime);
        calendar.add(Calendar.YEAR, 100);
        return calendar.getTime();
    }

    public String setSecretKey(SmartLock smartLock) {
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("嗨小克--密钥设置接口--token为空");
            return "0";
        }

        try {
            Map<String, Object> paramsMap = new HashMap<>(4);
            String notTime = this.haiXiaoKeParseDate(null);
            paramsMap.put("sendTime", notTime);
            paramsMap.put("randNonce", "123456");
            paramsMap.put("deviceMac", smartLock.getSn());
            paramsMap.put("secretKey", smartLock.getSecretKey());
            log.info("嗨小克--密钥设置请求参数：{}", paramsMap);
            HttpResponse response = HttpRequest.post(haiXiaoKeUrl + "/lock/setSecretKey").header("Authorization", token).body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            log.info("嗨小克--密钥设置响应参数：{}", response.body());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String code = jsonObject.getString("code");
                if ("0".equals(code)) {
                    return "1";
                } else {
                    log.error("嗨小克--密钥设置请求响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("嗨小克--密钥设置请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("嗨小克--密钥设置请求异常：{}", e.getMessage(), e);
        }
        return "0";
    }

    /**
     * 恢复出厂设置
     *
     * @param sn
     * @return
     */
    public String lockReset(SmartLock smartLock) {
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("嗨小克--恢复出厂设置接口--token为空");
            return "0";
        }

        try {
            Map<String, Object> paramsMap = new HashMap<>(4);
            String notTime = this.haiXiaoKeParseDate(null);
            paramsMap.put("sendTime", notTime);
            paramsMap.put("randNonce", "123456");
            paramsMap.put("deviceMac", smartLock.getSn());
            log.info("嗨小克--恢复出厂设置请求参数：{}", paramsMap);
            HttpResponse response = HttpRequest.post(haiXiaoKeUrl + "/lock/reset").header("Authorization", token).body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            log.info("嗨小克--恢复出厂设置响应参数：{}", response.body());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String code = jsonObject.getString("code");
                if ("0".equals(code)) {
                    return "1";
                } else {
                    log.error("嗨小克--恢复出厂设置请求响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("嗨小克--恢复出厂设置请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("嗨小克--恢复出厂设置请求异常：{}", e.getMessage(), e);
        }
        return "0";
    }

    public static void main(String[] args) {
        String result = "";
        String secretKey = "123456";
        Date now = DateUtil.date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHH");
        int a = (now.getMinutes() / 10 + 1) * 10;
        String time = "201902211615"/*simpleDateFormat.format(now) + (a - a % 10)*/;
        if (now.getMinutes() < 10) {
            time = simpleDateFormat.format(now) + "00";
        }

        //-----------------------------------
        //2023-08-11，wifi设备在计算离线密码时，需要使用后10位
        String mac = "1234500000";
        if (mac.length() == 12) {
            mac = StrUtil.sub(mac, 2, 10);
//            mac = mac.substring(2, 10);
        }
        //data可以多种算法:mac，secretKey，time任意顺序相加，可随机用一种
        //如data=mac+secretKey+time或data=secretKey+mac+time
//            String data = GetRandomData(mac, secretKey, time);
        String data = mac + secretKey + time;
        if (mac.length() == 12) {
            data = data.toLowerCase();
        }
        //计算sha1
        String encryptString = sha1(data);
        //按字节输出
        String strOut = "";
        if (encryptString.length() == 40) {

            strOut = StrUtil.sub(encryptString, 6, 6 + 2)
                    + StrUtil.sub(encryptString, 4, 4 + 2)
                    + StrUtil.sub(encryptString, 2, 2 + 2)
                    + StrUtil.sub(encryptString, 0, 2)

                    + StrUtil.sub(encryptString, 14, 14 + 2)
                    + StrUtil.sub(encryptString, 12, 12 + 2)
                    + StrUtil.sub(encryptString, 10, 10 + 2)
                    + StrUtil.sub(encryptString, 8, 8 + 2)

                    + StrUtil.sub(encryptString, 22, 22 + 2)
                    + StrUtil.sub(encryptString, 20, 20 + 2)
                    + StrUtil.sub(encryptString, 18, 18 + 2)
                    + StrUtil.sub(encryptString, 16, 16 + 2)

                    + StrUtil.sub(encryptString, 30, 30 + 2)
                    + StrUtil.sub(encryptString, 28, 28 + 2)
                    + StrUtil.sub(encryptString, 26, 26 + 2)
                    + StrUtil.sub(encryptString, 24, 24 + 2)

                    + StrUtil.sub(encryptString, 38, 38 + 2)
                    + StrUtil.sub(encryptString, 36, 36 + 2)
                    + StrUtil.sub(encryptString, 34, 34 + 2)
                    + StrUtil.sub(encryptString, 32, 32 + 2);

        }
//        strOut = strOut.toUpperCase();
        System.out.println("encryptString = " + encryptString);
        System.out.println("strOut = " + strOut);
        //每两个字节相异或再对10取模，得到10个字节，直接输前边8个数字给客户
        for (int i = 0; i < 40; i = i + 4) {


            String sub1 = StrUtil.sub(strOut, i, i + 2);
            String sub2 = StrUtil.sub(strOut, i + 2, i + 4);

            int h = Integer.parseInt(sub1, 16);
            int k = Integer.parseInt(sub2, 16);

//            long v1 = Long.parseLong(h);
//            long v2 = Long.parseLong(k);

            int v = h ^ k;
            int c = v % 10;
            result = result + c;
        }
//        result = StrUtil.sub(result, 0, 8);
//        result = result.substring(0, 8);
        System.out.println(result);
    }

    public String lockOTA(SmartLock smartLock) {
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("嗨小克--设备OTA升级接口--token为空");
            return "0";
        }

        try {
            Map<String, Object> paramsMap = new HashMap<>(4);
            String notTime = this.haiXiaoKeParseDate(null);
            paramsMap.put("sendTime", notTime);
            paramsMap.put("randNonce", "123456");
            paramsMap.put("deviceMac", smartLock.getSn());
            log.info("嗨小克--设备OTA升级请求参数：{}", paramsMap);
            HttpResponse response = HttpRequest.post(haiXiaoKeUrl + "/lock/otaUpgrade").header("Authorization", token).body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            log.info("嗨小克--设备OTA升级响应参数：{}", response.body());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String code = jsonObject.getString("code");
                if ("0".equals(code)) {
                    return "1";
                } else {
                    log.error("嗨小克--设备OTA升级请求响应数据异常：{}", jsonObject);
                }
            } else {
                log.error("嗨小克--设备OTA升级请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("嗨小克--设备OTA升级请求异常：{}", e.getMessage(), e);
        }
        return "0";
    }

    /**
     * 根据文件路径获取文件流
     *
     * @param imageUrl 文件路径
     * @return
     */
    public byte[] getOpenImage(String imageUrl) {
        String token = this.getToken();
        if (StrUtil.isEmpty(token)) {
            log.error("嗨小克--获取文件流接口--token为空");
            return null;
        }

        try {
            Map<String, Object> paramsMap = new HashMap<>(4);
            paramsMap.put("filename", imageUrl);
            HttpResponse response = HttpRequest.get(haiXiaoKeUrl + "/lock/getLockPhoto").header("Authorization", token).form(paramsMap).timeout(20000).execute();
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                return response.bodyBytes();
            } else {
                log.error("嗨小克--设备OTA升级请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("嗨小克--设备OTA升级请求异常：{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 删除嗨小克平台的业务数据
     * @param smartLock
     */
    public void deleteAppletSmartAuth(SmartLock smartLock) {
        try {
            Map<String, Object> paramsMap = new HashMap<>(4);
            paramsMap.put("sn", smartLock.getSn());

            String admin = RequestAesUtils.encrypt("admin");
            log.info("test嗨小克--删除嗨小克平台的用户授权的业务数据请求参数：{}",paramsMap);
            HttpResponse response = HttpRequest.post("https://qy.xjjaj.com/api/device/deleteAuth").header("Authorization", admin).body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            log.info("test嗨小克--删除嗨小克平台的用户授权的业务数据响应，code：{}；body:{}", response.getStatus(), response.body());

            log.info("prod嗨小克--删除嗨小克平台的用户授权的业务数据请求参数：{}",paramsMap);
            HttpResponse responseProd = HttpRequest.post("https://saas.runting2020.com/api/device/deleteAuth").header("Authorization", admin).body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            log.info("prod嗨小克--删除嗨小克平台的用户授权的业务数据响应，code：{}；body:{}", responseProd.getStatus(), responseProd.body());

        }catch (Exception e){
            log.error("嗨小克--删除嗨小克平台的用户授权的业务数据异常：{}",e.getMessage(),e);
        }
    }
}
